import 'package:cbec_app/components/base/base_chekbox.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

//积分抵扣弹窗

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class ScoreDiscountPopup extends StatefulWidget {
  final Map<String, dynamic> info;
  final Function(String discountAmount)? onConfirm;

  const ScoreDiscountPopup({super.key, required this.info, this.onConfirm});

  @override
  State<ScoreDiscountPopup> createState() => _ScoreDiscountPopup();
}

class _ScoreDiscountPopup extends State<ScoreDiscountPopup> {
  int _selected = 1;
  late TextEditingController scoreController;
  String inputPoints = '';

  @override
  void initState() {
    super.initState();
    scoreController = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    final keyboardHeight = MediaQuery.of(context).viewInsets.bottom; // 获取键盘高度

    return Container(
      width: 375.w,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(8),
          topRight: Radius.circular(8),
        ),
      ),
      child: Padding(
        padding: EdgeInsets.only(bottom: keyboardHeight), // 设置底部填充为键盘高度
        child: SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.only(top: 10.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    SizedBox(width: 18.w),
                    Text(
                      "积分",
                      style: setTextStyle(
                        14,
                        FontWeight.w500,
                        Tools.fromHex("#333333"),
                      ),
                    ),
                    Text(
                      " (剩余${widget.info['hasPoints'].toString()}积分)",
                      style: setTextStyle(
                        14,
                        FontWeight.w300,
                        Tools.fromHex("#333333"),
                      ),
                    ),
                  ],
                ),
                Container(
                  padding: EdgeInsets.fromLTRB(18.w, 10.w, 8.w, 10.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 选项1
                      Container(
                        margin: EdgeInsets.only(bottom: 10.w),
                        child: Row(
                          children: [
                            BaseCheckBox(
                              value: _selected == 1,
                              onChange: (selected) {
                                change(selected, 1);
                              },
                            ),
                            SizedBox(width: 10.w),
                            BaseInteractive(
                              onClick: () {
                                change(_selected != 1, 1);
                              },
                              childWidget: Text(
                                "暂时不用积分抵现",
                                style: setTextStyle(
                                  13,
                                  FontWeight.w300,
                                  Tools.fromHex("#333333"),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      // 选项2
                      Container(
                        margin: EdgeInsets.only(bottom: 10.w),
                        child: Row(
                          children: [
                            BaseCheckBox(
                              value: _selected == 2,
                              onChange: (selected) {
                                change(selected, 2);
                              },
                            ),
                            SizedBox(width: 10.w),
                            BaseInteractive(
                              onClick: () {
                                change(_selected != 2, 2);
                              },
                              childWidget: Text(
                                "最多可用${widget.info['maxUsePoints'].toString()}积分,抵现¥${widget.info['pointsMoney'].toString()}",
                                style: setTextStyle(
                                  13,
                                  FontWeight.w300,
                                  Tools.fromHex("#333333"),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      // 选项3和输入框

                      Container(
                        margin: EdgeInsets.only(bottom: 10.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                BaseCheckBox(
                                  value: _selected == 3,
                                  onChange: (selected) {
                                    change(selected, 3);
                                  },
                                ),
                                SizedBox(width: 10.w),
                                BaseInteractive(
                                  onClick: () {
                                    change(_selected != 3, 3);
                                  },
                                  childWidget: Text(
                                    "自定义积分数量",
                                    style: setTextStyle(
                                      13,
                                      FontWeight.w300,
                                      Tools.fromHex("#333333"),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(
                              width: 120.w,
                              child: Align(
                                alignment: Alignment.centerLeft,
                                child: SizedBox(
                                  width: 90.w,
                                  child: TextFormField(
                                    controller: scoreController,
                                    keyboardType: TextInputType.number,
                                    textAlign: TextAlign.center,
                                    decoration: const InputDecoration(
                                      hintText: "请输入积分数量",
                                      hintStyle: TextStyle(color: Colors.grey, fontSize: 12),
                                      isDense: true,
                                      contentPadding: EdgeInsets.only(bottom: 1.0),
                                      enabledBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(color: Colors.grey, width: 1.0),
                                      ),
                                      focusedBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(color: Colors.grey, width: 1.0),
                                      ),
                                    ),
                                    onChanged: (value) {
                                      inputPoints = value;
                                    },
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      const SizedBox(height: 20),
                      // 注意信息
                      SizedBox(
                        width: ScreenUtil().screenWidth,
                        child: const Text(
                          '注意:积分和预付卡同时使用时，请选择积分抵扣金额，再选择预付卡支付',
                          style: TextStyle(
                            color: ThemeConfig.themeColor,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 40),
                // 确认按钮
                Container(
                  padding: EdgeInsets.fromLTRB(18.w, 5.w, 18.w, 5.w),
                  width: 375.w,
                  color: Colors.white,
                  child: solidButton('确定', () {
                    submit();
                  }),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 选择逻辑
  void change(bool selected, int value) {
    setState(() {
      if (selected) {
        _selected = value;
      } else {
        _selected = 0;
      }
    });
  }

  // 提交逻辑
  void submit() {
    switch (_selected) {
      case 2: // 使用最大积分
        if (widget.onConfirm != null) {
          var usePointCost = widget.info['maxUsePoints'] / widget.info['pointsRadio'];
          widget.onConfirm!(usePointCost.toString());
        }
        Get.back();
        break;
      case 3: // 使用自定义积分
        if (inputPoints.isEmpty) {
          Tools.showToast('请输入积分数量');
          return;
        }

        var max = widget.info['maxUsePoints'];
        double canUse = double.parse(inputPoints);
        if (canUse > max) {
          Tools.showToast('超过最大可用积分，请重新输入');
          inputPoints = '';
          return;
        }

        if (widget.onConfirm != null) {
          var usePointCost = canUse / widget.info['pointsRadio'];
          String formattedUsePointCost = usePointCost.toStringAsFixed(2);
          widget.onConfirm!(formattedUsePointCost);
        }
        Get.back();
        break;
      case 1: // 不使用积分
      default:
        if (widget.onConfirm != null) {
          widget.onConfirm!('0');
        }
        Get.back();
    }
  }
}

/// 唤起积分抵扣弹窗
void showScoreDiscountPopup({required Map<String, dynamic> info, Function(String discountAmount)? onConfirm}) {
  showCupertinoModalPopup(
    barrierDismissible: false,
    context: Get.context!,
    builder: (context) {
      return ScoreDiscountPopup(
        info: info,
        onConfirm: onConfirm,
      );
    },
  );
}
